#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

int main()
{
    vector<Point> points; // 修改为存储Point类型的向量
    Vec4f lineParams;

    Mat img = imread("/home/lwj/opencv.21/2.png");
    if (img.empty())
    {
        cout << "无法加载图像" << endl;
        return -1;
    }

    Mat edges;
    cvtColor(img, edges, COLOR_BGR2GRAY); // 将图像转换为灰度图像
    Canny(edges, edges, 80, 180, 3, false);

    for (int i = 0; i < edges.rows; i++)
    {
        for (int j = 0; j < edges.cols; j++)
        {
            if (edges.at<uchar>(i, j) > 0) // 只将非零像素添加到向量中
            {
                points.push_back(Point(j, i));
            }
        }
    }

    fitLine(points, lineParams, DIST_L2, 0, 0.01, 0.01); // 使用DIST_L2距离类型

    float vx = lineParams[0];
    float vy = lineParams[1];
    float x0 = lineParams[2];
    float y0 = lineParams[3];
    
    float slope = vy / vx;
    float intercept = y0 - slope * x0;

    cout << "拟合直线方程为：y = " << slope << "x + " << intercept << endl;

    waitKey(0);

    return 0;
}